package eclipse_sync_plugin;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.part.ViewPart;
import org.eclipse.core.runtime.Platform;

/**
 * Eclipse插件控制视图
 * 提供插件的启动/停止控制，并处理F4快捷键事件
 * 负责连接Cursor插件的TCP服务
 */
public class PluginControlView extends ViewPart {
    /** 视图ID */
    public static final String ID = "eclipse_sync_plugin.PluginControlView";
    
    /** 启动/停止按钮 */
    private Button toggleButton;
    
    /** 插件活动状态标志 */
    private boolean isPluginActive = false;
    
    /** TCP客户端Socket */
    private Socket tcpClient;
    
    /** TCP服务器端口 */
    private static final int TCP_PORT = 9206;
    
    /** TCP服务器地址 */
    private static final String TCP_HOST = "127.0.0.1";
    
    /** 插件激活器实例 */
    private Activator activator;
    
    /** 光标位置记录器 */
    private CursorPositionWriter cursorPositionWriter;
    
    /** 快捷键监听器 */
    private Listener keyListener;
    
    /** TCP消息接收线程 */
    private Thread tcpReceiverThread;
    
    /** Python脚本的持久化路径 */
    private Path persistentScriptPath;

    /**
     * 构造函数
     * 初始化插件激活器
     */
    public PluginControlView() {
        activator = Activator.getDefault();
        this.cursorPositionWriter = new CursorPositionWriter();
        
        // 设置Python脚本的持久化路径
        String userHome = System.getProperty("user.home");
        Path syncPluginDir = Paths.get(userHome, ".eclipse-cursor-sync-plugin");
        this.persistentScriptPath = syncPluginDir.resolve("activate_cursor.py");
    }

    /**
     * 提取Python脚本到持久化位置
     */
    private void extractPythonScriptToPersistentLocation() throws IOException {
        // 确保目录存在
        Path parentDir = persistentScriptPath.getParent();
        if (!Files.exists(parentDir)) {
            Files.createDirectories(parentDir);
            activator.log(org.eclipse.core.runtime.Status.INFO, "创建持久化脚本目录: " + parentDir.toString(), null);
        }

        // 从jar包中读取Python脚本并复制到持久化位置
        try (InputStream is = getClass().getResourceAsStream("/activate_cursor.py")) {
            if (is == null) {
                throw new IOException("无法在jar包中找到Python脚本: /activate_cursor.py");
            }
            // 复制到持久化文件
            Files.copy(is, persistentScriptPath, StandardCopyOption.REPLACE_EXISTING);
            activator.log(org.eclipse.core.runtime.Status.INFO, "Python脚本已成功提取到持久化位置: " + persistentScriptPath.toString(), null);
        } catch (IOException e) {
            activator.log(org.eclipse.core.runtime.Status.ERROR, "提取Python脚本到持久化位置失败", e);
            throw e;
        }
    }

    /**
     * 创建视图控件
     * 设置布局、创建按钮并注册快捷键监听
     */
    @Override
    public void createPartControl(Composite parent) {
        // 设置布局
        parent.setLayout(new GridLayout(1, false));
        
        // 创建启动/停止按钮
        toggleButton = new Button(parent, SWT.PUSH);
        toggleButton.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false));
        toggleButton.setText("连接Cursor插件TCP服务");
        
        // 添加按钮点击事件
        toggleButton.addSelectionListener(new SelectionAdapter() {
            @Override
            public void widgetSelected(SelectionEvent e) {
                togglePlugin();
            }
        });

        // 添加F4快捷键监听
        addKeyListener();
    }

    /**
     * 切换插件状态
     * 启动或停止TCP连接，并更新按钮文本
     */
    private void togglePlugin() {
        if (activator != null) {
            if (!isPluginActive) {
                // 启动TCP连接
                try {
                    // 提取Python脚本
                    extractPythonScriptToPersistentLocation();
                    
                    connectToTcpServer();
                    toggleButton.setText("断开Cursor插件TCP服务");
                    isPluginActive = true;
                } catch (Exception ex) {
                    activator.log(org.eclipse.core.runtime.Status.ERROR, "连接TCP服务失败", ex);
                }
            } else {
                // 关闭TCP连接
                try {
                    disconnectFromTcpServer();
                    toggleButton.setText("连接Cursor插件TCP服务");
                    isPluginActive = false;
                    
                    // 删除Python脚本
                    try {
                        Files.deleteIfExists(persistentScriptPath);
                        activator.log(org.eclipse.core.runtime.Status.INFO, "已删除Python脚本: " + persistentScriptPath.toString(), null);
                    } catch (IOException e) {
                        activator.log(org.eclipse.core.runtime.Status.WARNING, "删除Python脚本失败", e);
                    }
                } catch (Exception ex) {
                    activator.log(org.eclipse.core.runtime.Status.ERROR, "断开TCP服务失败", ex);
                }
            }
        }
    }

    /**
     * 连接到TCP服务器
     */
    private void connectToTcpServer() throws IOException {
        tcpClient = new Socket(TCP_HOST, TCP_PORT);
        activator.log(org.eclipse.core.runtime.Status.INFO, "已连接到Cursor插件TCP服务", null);
        
        // 启动接收消息的线程
        //startTcpReceiver();
    }

    /**
     * 断开TCP连接
     */
    private void disconnectFromTcpServer() {
        if (tcpClient != null && !tcpClient.isClosed()) {
            try {
                tcpClient.close();
                activator.log(org.eclipse.core.runtime.Status.INFO, "已断开Cursor插件TCP服务", null);
            } catch (IOException e) {
                activator.log(org.eclipse.core.runtime.Status.ERROR, "断开TCP服务时发生错误", e);
            }
        }
        
        // 停止接收消息的线程
        if (tcpReceiverThread != null) {
            tcpReceiverThread.interrupt();
            tcpReceiverThread = null;
        }
    }

    /**
     * 启动TCP消息接收线程
     */
//    private void startTcpReceiver() {
//        tcpReceiverThread = new Thread(() -> {
//            try {
//                // 使用更大的缓冲区
//                BufferedReader reader = new BufferedReader(
//                    new InputStreamReader(tcpClient.getInputStream()), 8192);
//                String message;
//                while (!Thread.currentThread().isInterrupted() && (message = reader.readLine()) != null) {
//                    final String finalMessage = message;
//                    // 在UI线程中处理接收到的消息
//                    Display.getDefault().asyncExec(() -> {
//                        try {
//                            handleReceivedMessage(finalMessage);
//                            activator.log(org.eclipse.core.runtime.Status.INFO, 
//                                "成功接收并处理消息: " + finalMessage, null);
//                        } catch (Exception e) {
//                            activator.log(org.eclipse.core.runtime.Status.ERROR, 
//                                "处理接收到的消息时发生错误: " + finalMessage, e);
//                        }
//                    });
//                }
//            } catch (IOException e) {
//                if (!Thread.currentThread().isInterrupted()) {
//                    activator.log(org.eclipse.core.runtime.Status.ERROR, 
//                        "TCP消息接收错误: " + e.getMessage(), e);
//                    // 尝试重新连接
//                    try {
//                        Thread.sleep(5000); // 等待5秒后重试
//                        if (!Thread.currentThread().isInterrupted()) {
//                            connectToTcpServer();
//                        }
//                    } catch (Exception ex) {
//                        activator.log(org.eclipse.core.runtime.Status.ERROR, 
//                            "TCP重连失败", ex);
//                    }
//                }
//            }
//        });
//        tcpReceiverThread.setDaemon(true); // 设置为守护线程
//        tcpReceiverThread.start();
//    }

    /**
     * 处理接收到的TCP消息
     */
//    private void handleReceivedMessage(String message) {
//        if (message == null || message.trim().isEmpty()) {
//            activator.log(org.eclipse.core.runtime.Status.WARNING, 
//                "收到空消息", null);
//            return;
//        }
//        
//        try {
//            // 使用CursorPositionWriter处理接收到的消息
//            cursorPositionWriter.handleReceivedMessage(message);
//        } catch (Exception e) {
//            activator.log(org.eclipse.core.runtime.Status.ERROR, 
//                "处理消息时发生错误: " + message, e);
//        }
//    }

    /**
     * 通过TCP发送位置信息到Cursor
     */
    private void sendPositionToCursor(String positionJson) {
        if (tcpClient != null && !tcpClient.isClosed()) {
            try {
                PrintWriter writer = new PrintWriter(tcpClient.getOutputStream(), true);
                writer.println(positionJson);
            } catch (IOException e) {
                activator.log(org.eclipse.core.runtime.Status.ERROR, "发送位置信息失败", e);
            }
        }
    }

    /**
     * 添加F4快捷键监听
     */
    private void addKeyListener() {
        keyListener = new Listener() {
            @Override
            public void handleEvent(Event event) {
                if (event.keyCode == SWT.F4 && isPluginActive) {
                    // 获取当前活动编辑器
                    IEditorPart editor = getSite().getPage().getActiveEditor();
                    if (editor != null) {
                        // 获取光标位置信息
                        String positionJson = cursorPositionWriter.getCurrentPositionJson(editor);
                        if (positionJson != null) {
                            // 通过TCP发送数据
                            sendPositionToCursor(positionJson);
                            
                            // 调用Python脚本置顶Cursor窗口
                            try {
                                Process process = Runtime.getRuntime().exec("python \"" + persistentScriptPath.toString() + "\"");
                                // 读取Python脚本的输出
                                BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                                String line;
                                while ((line = reader.readLine()) != null) {
                                    activator.log(org.eclipse.core.runtime.Status.INFO, line, null);
                                }
                                process.waitFor();
                            } catch (Exception e) {
                                activator.log(org.eclipse.core.runtime.Status.ERROR, 
                                    "置顶Cursor窗口失败", e);
                            }
                        }
                    }
                }
            }
        };
        Display.getDefault().addFilter(SWT.KeyDown, keyListener);
    }

    @Override
    public void setFocus() {
        toggleButton.setFocus();
    }

    @Override
    public void dispose() {
        if (keyListener != null) {
            Display.getDefault().removeFilter(SWT.KeyDown, keyListener);
        }
        disconnectFromTcpServer();
        super.dispose();
    }
} 